package com.huishu.tcm.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.huishu.tcm.entity.*;
import com.huishu.tcm.service.*;
import com.huishu.tcm.util.AESUtil;
import com.huishu.tcm.util.Constants;
import com.huishu.tcm.util.RateLimit;
import com.huishu.tcm.util.SmsUtil;
import com.huishu.tcm.util.exception.TcmException;
import com.huishu.tcm.util.exception.TcmExceptionEnum;
import com.huishu.tcm.vo.SmsResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huishu.tcm.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

@Api(tags = "用户表")
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController extends BaseController<UserService> {

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键查询一条数据", notes = "根据主键查询一条数据")
    @RequestMapping(method = RequestMethod.GET)
    public User get(@RequestParam String id) throws TcmException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        User u = service.getOne(wrapper);
        // 用户信息脱敏
        AESUtil.userInfoDesensitization(u);
        return u;
    }

    /**
     * 查询数据列表
     * @return
     */
    @ApiOperation(value = "根据筛选条件查询数据列表", notes = "根据筛选条件查询数据列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public List<User> list(@RequestBody User v) throws TcmException {
        QueryWrapper<User> queryWrapper = service.getQueryWrapper(v);
        List<User> list = service.list(queryWrapper);
        for(User u : list ){
            // 用户信息脱敏
            AESUtil.userInfoDesensitization(u);
        }
        return list;
    }

    /**
     * 分页查询数据列表
     * @param pageVo
     * @return
     */
    @ApiOperation(value = "根据筛选条件分页查询数据列表", notes = "根据筛选条件分页查询数据列表")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public Page<User> page(@RequestBody PageVo<User> pageVo) throws TcmException {
        User v = pageVo.getEntity();
        QueryWrapper<User> wrapper = service.getQueryWrapper(v);
        Page<User> page = new Page<>(pageVo.getPage(),pageVo.getLimit());
        page = service.page(page,wrapper);
        for(User u : page.getRecords()){
            // 用户信息脱敏
            AESUtil.userInfoDesensitization(u);
        }
        return page;
    }

    /**
     * 添加
     * @param v
     * @return
     */
    @ApiOperation(value = "添加一条数据",notes = "添加一条数据")
    @RequestMapping(method = RequestMethod.POST)
    public boolean save(@RequestBody User v) throws Exception {
        return service.save(v);
    }

    /**
     * 根据主键更新
     * @param v
     * @return
     */
    @ApiOperation(value = "根据主键更新数据",notes = "根据主键更新数据")
    @RequestMapping(method = RequestMethod.PUT)
    public boolean update(@RequestBody User v) throws Exception {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", v.getId());
        return service.update(v,queryWrapper);
    }


    /**
     * 根据主键删除
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键删除数据",notes = "根据主键删除数据")
    @RequestMapping(method = RequestMethod.DELETE)
    public boolean removeById(@RequestParam Integer id){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        return service.remove(wrapper);
    }


    @Resource
    Annex4Service annex4Service; // 身体测量及静脉血筛查记录表
    @Resource
    Annex2Service annex2Service; // 糖尿病前期患者生活方式调查问卷
    @Resource
    Annex6Service annex6Service; // 中医证候积分量表

    @ApiOperation(value = "查询中医证候积分量表和身体测量及静脉血筛查记录表末次填写是否完成")
    @GetMapping(value = "/queryAnnex6And4TheLastTimeIsOver", params = {"patientId"})
    public Map<String, Boolean> queryAnnex6And4TheLastTimeIsOver(int patientId){
        QueryWrapper<Annex6> annex6QueryWrapper = new QueryWrapper<>();
        annex6QueryWrapper.eq("patient_id", patientId);
        annex6QueryWrapper.eq("the_last_time", true);
        List<Annex6> annex6s = annex6Service.list(annex6QueryWrapper);

        QueryWrapper<Annex4> annex4QueryWrapper = new QueryWrapper<>();
        annex4QueryWrapper.eq("patient_id", patientId);
        annex4QueryWrapper.eq("the_last_time", true);
        List<Annex4> annex4s = annex4Service.list(annex4QueryWrapper);

        Map<String, Boolean> map = new HashMap<>();
        map.put("annex6",false);
        map.put("annex4",false);
        if(ObjectUtil.isNotEmpty(annex6s)){
            map.put("annex6", true);
        }
        if(ObjectUtil.isNotEmpty(annex4s)){
            map.put("annex4", true);
        }
        return map;
    }


    @ApiOperation(value = "查询糖尿病前期患者生活方式调查问卷和身体测量及静脉血筛查记录表末次填写是否完成",
        notes = "返回值：{annex2:true、false, annex4:true、false}")
    @GetMapping(value = "/queryAnnex2And4TheLastTimeIsOver", params = {"patientId"})
    public Map<String, Boolean> queryAnnex2And4TheLastTimeIsOver(int patientId){
        QueryWrapper<Annex2> annex2QueryWrapper = new QueryWrapper<>();
        annex2QueryWrapper.eq("patient_id", patientId);
        annex2QueryWrapper.eq("the_last_time", true);
        List<Annex2> annex2s = annex2Service.list(annex2QueryWrapper);

        QueryWrapper<Annex4> annex4QueryWrapper = new QueryWrapper<>();
        annex4QueryWrapper.eq("patient_id", patientId);
        annex4QueryWrapper.eq("the_last_time", true);
        List<Annex4> annex4s = annex4Service.list(annex4QueryWrapper);

        Map<String, Boolean> map = new HashMap<>();
        map.put("annex2",false);
        map.put("annex4",false);
        if(ObjectUtil.isNotEmpty(annex2s)){
            map.put("annex2", true);
        }
        if(ObjectUtil.isNotEmpty(annex4s)){
            map.put("annex4", true);
        }
        return map;
    }

    @Resource
    Annex7Service annex7Service;

    @ApiOperation(value = "查询中医健康管理随访监测记录表末次填写是否完成", notes = "返回值：{annex7: true、false}")
    @GetMapping(value = "/queryAnnex7TheLastTimeIsOver", params = {"patientId"})
    public Map<String,Boolean> queryAnnex7TheLastTimeIsOver(int patientId){
        QueryWrapper<Annex7> annex7QueryWrapper = new QueryWrapper<>();
        annex7QueryWrapper.eq("patient_id", patientId);
        annex7QueryWrapper.eq("the_last_time", true);
        List<Annex7> annex7s = annex7Service.list(annex7QueryWrapper);
        Map<String, Boolean> map = new HashMap<>();
        map.put("annex7", false);
        if(ObjectUtil.isNotEmpty(annex7s)){
            map.put("annex7",true);
        }
        return map;
    }
    @Resource
    Annex9Service annex9Service;

    @ApiOperation(value = "查询糖尿病患者中医干预随访记录末次填写是否完成", notes = "返回值：{annex9: true、false}")
    @GetMapping(value = "/queryAnnex9TheLastTimeIsOver", params = {"patientId"})
    public Map<String,Boolean> queryAnnex9TheLastTimeIsOver(int patientId){
        QueryWrapper<Annex9> annex9QueryWrapper = new QueryWrapper<>();
        annex9QueryWrapper.eq("patient_id", patientId);
        annex9QueryWrapper.eq("the_last_time", true);
        List<Annex9> annex9s = annex9Service.list(annex9QueryWrapper);
        Map<String, Boolean> map = new HashMap<>();
        map.put("annex9", false);
        if(ObjectUtil.isNotEmpty(annex9s)){
            map.put("annex9",true);
        }
        return map;
    }
    /**
     * 结束患者管理
     * @param patientId 患者用户id
     */
    @ApiOperation(value = "结束患者管理", notes= "结束患者管理")
    @GetMapping(value = "/endManagementPatient", params = {"patientId"})
    public void endManagementPatient(int patientId){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", patientId);
        User user = service.getOne(queryWrapper);
        user.setEndManagement(true);
        service.update(user, queryWrapper);
    }

    /**
     * 未填表时取消提醒
     * @param patientId 患者用户id
     */
    @ApiOperation(value = "未填表时取消提醒", notes= "未填表时取消提醒")
    @GetMapping(value = "/notRemind", params = {"patientId"})
    public void notRemind(int patientId){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", patientId);
        User user = service.getOne(queryWrapper);
        user.setNotRemind(true);
        service.update(user, queryWrapper);
    }

    // 查询15天未填表的用户
    @ApiOperation(value = "查询15天未填表的用户列表", notes= "查询15天未填表的用户列表")
    @GetMapping(value = "/queryUser15DaysNotFilledAnnex", params = {"institutionId"})
    public List<User> queryUser15DaysNotFilledAnnex(int institutionId){
        Date day15Ago = new Date(new Date().getTime() - 15 * 24 * 60 * 60 * 1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("institution_id", institutionId);
        queryWrapper.ne("not_remind", true);
        queryWrapper.lt("create_time", sdf.format(day15Ago));
        List<User> list =  service.list(queryWrapper);
        for(User u : list){
            // 用户信息脱敏
            AESUtil.userInfoDesensitization(u);
        }
        return list;
    }

    // 在未完成列表删除该用户
    @ApiOperation(value = "在未完成列表删除该用户", notes = "在未完成列表删除该用户")
    @GetMapping(value = "/deleteFromIncompleteList", params = {"patientId"})
    public void deleteFromIncompleteList(int patientId){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", patientId);
        User user = service.getOne(queryWrapper);
        user.setIncompleteListDeleted(true);
        service.update(user,queryWrapper);
    }


    @ApiOperation(value = "审核医生注册信息", notes= "审核医生注册信息：通过or拒绝")
    @GetMapping(value = "/reviewedDoctorRegisterInfo", params = {"doctorId", "isPass"})
    public void reviewedDoctorRegisterInfo(int doctorId,boolean isPass) throws Exception {
        // 判断登录用户是否为管理员用户
        User loginUser = getLoginUser();
        if(Constants.USER_ROLE_ADMIN.equals(loginUser.getRole())){
            User user = service.getById(doctorId);
            if(isPass){
                user.setRegisterStatus(Constants.USER_REGISTER_STATUS_success);
                SmsResponseVo responseVo = SmsUtil.sendDoctorRegisterSuccessSms(user.getTelNum(), true);
                log.info( "发送验证码返回值：" + JSONObject.toJSONString(responseVo));
            }else{
                user.setRegisterStatus(Constants.USER_REGISTER_STATUS_failed);
                SmsResponseVo responseVo = SmsUtil.sendDoctorRegisterSuccessSms(user.getTelNum(), false);
                log.info( "发送验证码返回值：" + JSONObject.toJSONString(responseVo));
            }
            service.updateById(user);
            return;
        }
        throw new TcmException(TcmExceptionEnum.USER_ACCOUN_NO_AUTHORITY);
    }

    @Resource
    Annex1Service annex1Service;
    @Resource
    Annex5Service annex5Service;
    @Resource
    Annex8Service annex8Service;
    @Resource
    CustomizeService customizeService;
    @Resource
    PrescriptionDietService prescriptionDietService;
    @Resource
    PrescriptionHealthEducationService prescriptionHealthEducationService;
    @Resource
    PrescriptionLoseWeightService prescriptionLoseWeightService;
    @Resource
    PrescriptionMotionService prescriptionMotionService;
    @Resource
    PrescriptionOtherService prescriptionOtherService;
    @Resource
    PrescriptionPhysiqueService prescriptionPhysiqueService;
    @Resource
    PrescriptionSleepService prescriptionSleepService;

    @RateLimit()
    @ApiOperation(value = "导出：注册的患者是否已填写数据", notes = "注册已填写 注册未填写")
    @GetMapping(value = "/exportRegisterPatientIsFillIn")
    public void exportRegisterPatientIsFillIn() throws ClassNotFoundException, NoSuchMethodException, IOException {
        // 查询患者信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("role", "patient");
        List<User> patientList = service.list(userQueryWrapper);
        List<Map<String,String>> resultList = new ArrayList<>();
        List list;
        Map<String,String> map;
        for(User patient: patientList){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("patient_id", patient.getId());
            list = annex1Service.list(queryWrapper);
            map = new HashMap<>();
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = annex2Service.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = annex4Service.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = annex5Service.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = annex6Service.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = annex7Service.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = annex8Service.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map = new HashMap<>();
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = customizeService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionDietService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionHealthEducationService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionLoseWeightService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionMotionService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionOtherService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionPhysiqueService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            list = prescriptionSleepService.list(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)){
                map.put("name",patient.getName());
                map.put("value","已填写");
                resultList.add(map);
                continue;
            }
            map.put("name",patient.getName());
            map.put("value","未填写");
            resultList.add(map);
        }
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("姓名");
        cell = row.createCell(1);
        cell.setCellValue("是否填写");

        for(int i = 0; i < resultList.size();i++){
            row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellValue(resultList.get(i).get("name"));
            cell = row.createCell(1);
            cell.setCellValue(resultList.get(i).get("value"));
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        workbook.close();
        out.close();
    }
}
